package com.jeecg.o2o.businesses.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.jeecgframework.core.beanvalidator.BeanValidators;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ExceptionUtil;
import org.jeecgframework.core.util.FileUtils;
import org.jeecgframework.core.util.LocationUtils;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.jwt.util.ResponseMessage;
import org.jeecgframework.jwt.util.Result;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.UriComponentsBuilder;

import com.alibaba.fastjson.JSON;
import com.jeecg.o2o.bCategories.entity.BcategoriesEntity;
import com.jeecg.o2o.bCategories.service.BcategoriesServiceI;
import com.jeecg.o2o.bGoods.entity.BgoodsEntity;
import com.jeecg.o2o.bGoods.service.BgoodsServiceI;
import com.jeecg.o2o.businesses.entity.Businessesbean;
import com.jeecg.o2o.businesses.entity.MenuList;
import com.jeecg.o2o.businesses.entity.TbBusinessesEntity;
import com.jeecg.o2o.businesses.service.TbBusinessesServiceI;
import com.jeecg.o2o.tbimage.entity.TbimageEntity;
import com.jeecg.o2o.tbimage.service.TbimageServiceI;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * @Title: Controller
 * @Description: 商家列表
 * @author onlineGenerator
 * @date 2019-02-09 16:01:58
 * @version V1.0
 *
 */
@Api(value = "TbBusinesses", description = "商家列表", tags = "tbBusinessesController")
@Controller
@RequestMapping("/tbBusinessesController")
public class TbBusinessesController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(TbBusinessesController.class);

	@Autowired
	private TbBusinessesServiceI tbBusinessesService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private Validator validator;
	@Autowired
	private BcategoriesServiceI bcategoriesService;
	@Autowired
	private BgoodsServiceI bgoodsService;
	@Autowired
	private TbimageServiceI tbimageServiceI;

	/**
	 * 商家列表列表 页面跳转
	 * 
	 * @return
	 */

	@RequestMapping(params = "list")
	@ResponseBody
	@ApiOperation(value = "商家列表列表信息", produces = "application/json", httpMethod = "Post")
	public ResponseMessage<List<Businessesbean>> list(HttpServletRequest request,
			@ApiParam(name = "商家列表对象") @RequestBody Businessesbean Businessesbean) {

		// 计算所有商铺距离用户的距离
		List<TbBusinessesEntity> ls = this.tbBusinessesService.findHql("from TbBusinessesEntity where status=?", "1");
		List<Businessesbean> returnls = new ArrayList<Businessesbean>();
		for (TbBusinessesEntity tbBusinessesEntity : ls) {
			String[] locat = tbBusinessesEntity.getCoordinate().split(";");
			String lat2 = locat[0];
			String lng2 = locat[1];
			double location = LocationUtils.getDistance(Double.valueOf(Businessesbean.getLatitude()),
					Double.valueOf(Businessesbean.getLongitude()), Double.valueOf(lat2), Double.valueOf(lng2));
			if (location <= Double
					.valueOf(!Businessesbean.getOffset().equals("0") ? Businessesbean.getOffset() : "200000")) {
				Businessesbean businessesbean = new Businessesbean();
				businessesbean.setLogocode(tbBusinessesEntity.getLogocode());
				businessesbean.setName(tbBusinessesEntity.getName());
				businessesbean.setId(String.valueOf(tbBusinessesEntity.getId()));
				businessesbean.setLatitude("333");
				businessesbean.setLongitude("9999");
				returnls.add(businessesbean);
			}
		}

		return Result.success(returnls);
	}

	@RequestMapping(params = "getentry")
	@ResponseBody
	@ApiOperation(value = "商家列表列表信息", produces = "application/json", httpMethod = "Post")
	public ResponseMessage<TbBusinessesEntity> getentry(HttpServletRequest request,
			@ApiParam(name = "商家列表对象") @RequestBody Businessesbean Businessesbean) {

		// 计算所有商铺距离用户的距离
		TbBusinessesEntity BusinessesEntity = this.tbBusinessesService.get(TbBusinessesEntity.class,
				Integer.valueOf(Businessesbean.getShopid()));
		return Result.success(BusinessesEntity);
	}

	/**
	 * 处理移动端根据商户id请求 获取商户的菜单--categories 根据菜单--categories获取对应的菜品
	 */

	@RequestMapping(params = "menu")
	@ResponseBody
	@ApiOperation(value = "商家列表列表信息", produces = "application/json", httpMethod = "Post")
	public ResponseMessage<List<MenuList>> menu(HttpServletRequest request,
			@ApiParam(name = "商家列表对象") @RequestBody Businessesbean Businessesbean) {

		// 计算所有商铺距离用户的距离
		TbBusinessesEntity BusinessesEntity = this.tbBusinessesService.get(TbBusinessesEntity.class,
				Integer.valueOf(Businessesbean.getRestaurant_id()));
		List<MenuList> menuList = new ArrayList<MenuList>();
		// 获取种类（菜单）
		if (BusinessesEntity != null) {
			List<BcategoriesEntity> BcategoriesEntityls = bcategoriesService.getList(BcategoriesEntity.class,
					BusinessesEntity.getUid());
			// 根据种类获取商品
			if (BcategoriesEntityls != null && BcategoriesEntityls.size() > 0) {

				for (BcategoriesEntity bcategoriesEntity : BcategoriesEntityls) {
					MenuList Menu = new MenuList();
					// List<BgoodsEntity> goodsentiryls = new ArrayList<BgoodsEntity>();
					List<BgoodsEntity> goodsls = bgoodsService.queryPreEntrylist(BgoodsEntity.class,
							BusinessesEntity.getUid(), "categoriesid=?", bcategoriesEntity.getId());

					for (BgoodsEntity BgoodsEntity : goodsls) {
						TbimageEntity TbimageEntity = this.tbimageServiceI.getEntity(TbimageEntity.class,
								BgoodsEntity.getGoodimg());
						BgoodsEntity.setGoodimgcode(TbimageEntity.getCode());
						BgoodsEntity.setNum(0);
					}
					Menu.setName(bcategoriesEntity.getName());
					Menu.setFoods(goodsls);
					Menu.setType("1");
					menuList.add(Menu);
				}
				// menuList.setFoods(goodsentiryls);

			}
		}

		return Result.success(menuList);
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */
	@RequestMapping(params = "datagrid")
	public void datagrid(TbBusinessesEntity tbBusinesses, HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(TbBusinessesEntity.class, dataGrid);
		// 查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tbBusinesses,
				request.getParameterMap());
		cq.add();
		this.tbBusinessesService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除商家列表
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(TbBusinessesEntity tbBusinesses, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		tbBusinesses = systemService.getEntity(TbBusinessesEntity.class, tbBusinesses.getId());
		message = "商家列表删除成功";
		try {
			tbBusinessesService.delete(tbBusinesses);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "商家列表删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 批量删除商家列表
	 * 
	 * @return
	 */
	@RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "商家列表删除成功";
		try {
			for (String id : ids.split(",")) {
				TbBusinessesEntity tbBusinesses = systemService.getEntity(TbBusinessesEntity.class,
						Integer.parseInt(id));
				tbBusinessesService.delete(tbBusinesses);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		} catch (Exception e) {
			e.printStackTrace();
			message = "商家列表删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 添加商家列表
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(TbBusinessesEntity tbBusinesses, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "商家列表添加成功";
		try {
			tbBusinessesService.save(tbBusinesses);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "商家列表添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 更新商家列表
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(TbBusinessesEntity tbBusinesses, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "商家列表更新成功";
		TbBusinessesEntity t = tbBusinessesService.get(TbBusinessesEntity.class, tbBusinesses.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(tbBusinesses, t);
			tbBusinessesService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "商家列表更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 导入功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name", "tbBusinessesController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}

	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(TbBusinessesEntity tbBusinesses, HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid, ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(TbBusinessesEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tbBusinesses,
				request.getParameterMap());
		List<TbBusinessesEntity> tbBusinessess = this.tbBusinessesService.getListByCriteriaQuery(cq, false);
		modelMap.put(NormalExcelConstants.FILE_NAME, "商家列表");
		modelMap.put(NormalExcelConstants.CLASS, TbBusinessesEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS,
				new ExportParams("商家列表列表", "导出人:" + ResourceUtil.getSessionUser().getRealName(), "导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST, tbBusinessess);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}

	/**
	 * 导出excel 使模板
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(TbBusinessesEntity tbBusinesses, HttpServletRequest request,
			HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap) {
		modelMap.put(NormalExcelConstants.FILE_NAME, "商家列表");
		modelMap.put(NormalExcelConstants.CLASS, TbBusinessesEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS,
				new ExportParams("商家列表列表", "导出人:" + ResourceUtil.getSessionUser().getRealName(), "导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST, new ArrayList());
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<TbBusinessesEntity> listTbBusinessesEntitys = ExcelImportUtil.importExcel(file.getInputStream(),
						TbBusinessesEntity.class, params);
				for (TbBusinessesEntity tbBusinesses : listTbBusinessesEntitys) {
					tbBusinessesService.save(tbBusinesses);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}

	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "商家列表列表信息", produces = "application/json", httpMethod = "GET")
	public ResponseMessage<List<TbBusinessesEntity>> list() {
		List<TbBusinessesEntity> listTbBusinessess = tbBusinessesService.getList(TbBusinessesEntity.class);
		return Result.success(listTbBusinessess);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "根据ID获取商家列表信息", notes = "根据ID获取商家列表信息", httpMethod = "GET", produces = "application/json")
	public ResponseMessage<?> get(@ApiParam(required = true, name = "id", value = "ID") @PathVariable("id") String id) {
		TbBusinessesEntity task = null;
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		String shopuid = request.getHeader("shopuid");
		if (shopuid != null && !shopuid.trim().equals("")) {
			task = tbBusinessesService.findUniqueByProperty(TbBusinessesEntity.class, "uid", shopuid);
		} else {
			task = tbBusinessesService.get(TbBusinessesEntity.class, id);
		}

		if (task == null) {
			return Result.error("根据ID获取商家列表信息为空");
		}
		return Result.success(task);
	}

	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "创建商家列表")
	public ResponseMessage<?> create(@ApiParam(name = "商家列表对象") @RequestBody TbBusinessesEntity tbBusinesses,
			UriComponentsBuilder uriBuilder) {
		// 调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<TbBusinessesEntity>> failures = validator.validate(tbBusinesses);
		if (!failures.isEmpty()) {
			return Result.error(JSON.toJSONString(BeanValidators.extractPropertyAndMessage(failures)));
		}

		// 保存
		try {
			tbBusinessesService.save(tbBusinesses);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("商家列表信息保存失败");
		}
		return Result.success(tbBusinesses);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "更新商家列表", notes = "更新商家列表")
	public ResponseMessage<?> update(@ApiParam(name = "商家列表对象") @RequestBody TbBusinessesEntity tbBusinesses) {
		// 调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<TbBusinessesEntity>> failures = validator.validate(tbBusinesses);
		if (!failures.isEmpty()) {
			return Result.error(JSON.toJSONString(BeanValidators.extractPropertyAndMessage(failures)));
		}

		// 保存
		try {
			tbBusinessesService.saveOrUpdate(tbBusinesses);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("更新商家列表信息失败");
		}

		// 按Restful约定，返回204状态码, 无内容. 也可以返回200状态码.
		return Result.success("更新商家列表信息成功");
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ResponseStatus(HttpStatus.NO_CONTENT)
	@ApiOperation(value = "删除商家列表")
	public ResponseMessage<?> delete(
			@ApiParam(name = "id", value = "ID", required = true) @PathVariable("id") String id) {
		logger.info("delete[{}]" + id);
		// 验证
		if (StringUtils.isEmpty(id)) {
			return Result.error("ID不能为空");
		}
		try {
			tbBusinessesService.deleteEntityById(TbBusinessesEntity.class, id);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("商家列表删除失败");
		}

		return Result.success();
	}

	@RequestMapping(value = "/update/avatar/{id}", method = RequestMethod.POST, consumes = "multipart/form-data")
	@ResponseBody
	@ApiOperation(value = "提交logo保存", notes = "提交logo保存", httpMethod = "POST")
	public ResponseMessage<?> updateavatar(
			@ApiParam(required = true, name = "id", value = "ID") @PathVariable("id") String id,
			HttpServletRequest request) {
		TbBusinessesEntity task = null;
		String shopuid = request.getHeader("shopuid");

		task = tbBusinessesService.get(TbBusinessesEntity.class, Integer.valueOf(id));

		if (shopuid != null && !shopuid.trim().equals("")) {
			long startTime = System.currentTimeMillis();
			// 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 检查form中是否有enctype="multipart/form-data"
			if (multipartResolver.isMultipart(request)) {
				// 将request变成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 获取multiRequest 中所有的文件名
				Iterator iter = multiRequest.getFileNames();
				String path = "";
				while (iter.hasNext()) {
					// 一次遍历所有文件
					MultipartFile file = multiRequest.getFile(iter.next().toString());
					if (file != null) {
						path = "C:/springUpload/" + file.getOriginalFilename();
						task.setLogo(file.getOriginalFilename());
						// 上传
						try {
							file.transferTo(new File(path));
						} catch (IllegalStateException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}

				}
				File f = new File(path);
				// 获取图片格式
				String ext = FileUtils.getImageFormat(f);
				task.setLogoext(ext);
				String encodeimg = "data:image/" + ext + ";base64,";
				BufferedImage bi = null;
				try {
					bi = ImageIO.read(f);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				try {
					ImageIO.write(bi, "jpg", baos);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				byte[] bytes = baos.toByteArray();
				String encodeimgall = encodeimg + Base64.encodeBase64String(bytes);
				task.setLogocode(bytes);
				System.out.println("字节6666：" + encodeimgall);
				task.setLogocodeStr(encodeimgall);
				try {
					tbBusinessesService.saveOrUpdate(task);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			long endTime = System.currentTimeMillis();
			System.out.println("方法三的运行时间：" + String.valueOf(endTime - startTime) + "ms");

		} else {
			task = tbBusinessesService.get(TbBusinessesEntity.class, id);
		}

		if (task == null) {
			return Result.error("根据ID获取商家列表信息为空");
		}
		return Result.success(task);
	}
}
